//------------------------------------------------------------------------------
// <copyright company="Telligent Systems">
//     Copyright (c) Telligent Systems Corporation.  All rights reserved.
// </copyright> 
//------------------------------------------------------------------------------

using System;
using System.Web.UI.WebControls;
using CommunityServer.Blogs.Components;
using CommunityServer.Components;
using CommunityServer.Controls;
using CommunityServer;

namespace CommunityServer.Blogs.Controls
{
	/// <summary>
	/// Weblog Contact Form control
	/// </summary>
	public class ContactForm : WeblogThemedControl
	{
		public ContactForm()
		{
		}

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad (e);
            if(!CurrentWeblog.ShowContact)
            {
                Context.Response.StatusCode = 404;
                Context.Response.SuppressContent = true;
                Context.Response.End();
            }

            SetPageTitle("Contact");

			CSContext context = CSContext.Current;
			TextBox tbName = FindControl("tbName") as TextBox;
			if (tbName != null && !context.User.IsAnonymous)
				tbName.Text = context.User.CommonNameOrUserName;

        }

        /// <summary>
	    /// Override this method to attach templated or external skin controls to local references.
	    /// </summary>
	    /// <remarks>
	    /// This will only be called if the non-default skin is used.
	    /// </remarks>
	    protected override void AttachChildControls()
	    {
			IButton btnSubmit = FindButton("btnSubmit");
			btnSubmit.Click +=new EventHandler(btnSubmit_Click);
			btnSubmit.Text = ResourceManager.GetString("Weblog_ContactForm_Button");
        }

        private void btnSubmit_Click(object sender, EventArgs e)
        {
			IText Msg = FindText("Msg");
			if(Msg != null)
				Msg.Text = string.Empty;

			if(!Page.IsValid)
				return;

			TextBox tbName = FindControl("tbName") as TextBox;
			TextBox tbSubject = FindControl("tbSubject") as TextBox;
			TextBox tbEmail = FindControl("tbEmail") as TextBox;
			TextBox tbBody = FindControl("tbBody") as TextBox;

			// Check for null Name & Subject textboxes in case blog skin does not use them
			string name = string.Empty;
			if (tbName != null)
				name = tbName.Text;

			string subject = string.Empty;
			if (tbSubject != null)
				subject = tbSubject.Text;

			string link = Globals.HostPath(Context.Request.Url) + BlogUrls.Instance().HomePage(CurrentWeblog.ApplicationKey);
			Emails.QueueContactRequest(CurrentWeblog.Email, tbEmail.Text, subject, tbBody.Text, CurrentWeblog.Name, link, name);

			if(Msg != null)
				Msg.Text = ResourceManager.GetString("Weblog_ContactForm_Sent");

        }
    }
}
